﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ShiQuan.Access.Helper;

namespace ShiQuan.WinControls
{
    public class UCDataTable: UserControl
    {
        private ToolStrip sysToolBar;
        private ToolStripButton tbbSave;
        private ToolStripButton tbbRefresh;
        private DataGridView dataGridView1;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UCDataTable));
            this.sysToolBar = new System.Windows.Forms.ToolStrip();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.tbbSave = new System.Windows.Forms.ToolStripButton();
            this.tbbRefresh = new System.Windows.Forms.ToolStripButton();
            this.sysToolBar.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // sysToolBar
            // 
            this.sysToolBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tbbSave,
            this.tbbRefresh});
            this.sysToolBar.Location = new System.Drawing.Point(0, 0);
            this.sysToolBar.Name = "sysToolBar";
            this.sysToolBar.Size = new System.Drawing.Size(757, 25);
            this.sysToolBar.TabIndex = 0;
            this.sysToolBar.Text = "toolStrip1";
            // 
            // dataGridView1
            // 
            this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Window;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dataGridView1.Location = new System.Drawing.Point(0, 25);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowTemplate.Height = 23;
            this.dataGridView1.Size = new System.Drawing.Size(757, 485);
            this.dataGridView1.TabIndex = 1;
            // 
            // tbbSave
            // 
            this.tbbSave.Image = ((System.Drawing.Image)(resources.GetObject("tbbSave.Image")));
            this.tbbSave.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.tbbSave.Name = "tbbSave";
            this.tbbSave.Size = new System.Drawing.Size(67, 22);
            this.tbbSave.Text = "保存(&S)";
            // 
            // tbbRefresh
            // 
            this.tbbRefresh.Image = ((System.Drawing.Image)(resources.GetObject("tbbRefresh.Image")));
            this.tbbRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.tbbRefresh.Name = "tbbRefresh";
            this.tbbRefresh.Size = new System.Drawing.Size(67, 22);
            this.tbbRefresh.Text = "刷新(&R)";
            // 
            // UCDataTable
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.sysToolBar);
            this.Name = "UCDataTable";
            this.Size = new System.Drawing.Size(757, 510);
            this.sysToolBar.ResumeLayout(false);
            this.sysToolBar.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private TabControl tabControl = null;

        public UCDataTable()
        {
            this.InitializeComponent();
        }

        public UCDataTable(TabControl tabControl)
        {
            this.InitializeComponent();

            this.tabControl = tabControl;
            this.Load += UCDataTable_Load;
        }

        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DBFileName
        {
            get;
            set;
        }
        /// <summary>
        /// 数据表名称
        /// </summary>
        public string TableName
        {
            get;
            set;
        }
        private DataTable dtData = null;
        void UCDataTable_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
                return;

            //设置双缓冲，解决datagridview 显示数据缓慢
            Type type = dataGridView1.GetType();
            System.Reflection.PropertyInfo pi = type.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            pi.SetValue(dataGridView1, true, null);
            //this.tbbDelete.Click += tbbDelete_Click;
            this.tbbSave.Click += tbbSave_Click;
            //this.tbbReset.Click += tbbReset_Click;
            this.tbbRefresh.Click += tbbRefresh_Click;

            this.LoadData();
        }

        void tbbRefresh_Click(object sender, EventArgs e)
        {
            this.LoadData();
        }

        void tbbSave_Click(object sender, EventArgs e)
        {
            this.dataGridView1.EndEdit();
            this.dataGridView1.CurrentCell = null;
            DataTable dtChanges = dtData.GetChanges();
            if (dtChanges == null || dtChanges.Rows.Count <= 0)
            {
                return;
            }
            try
            {
                OleDbHelper dbHelper = new OleDbHelper(this.DBFileName);
                DataTable dtColumns = dbHelper.GetColumns(this.TableName);
                DataRow[] drPrimaryKeys = dtColumns.Select("PrimaryKey='1'");
                if (drPrimaryKeys.Length <= 0)
                {
                    WinMessageBox.Show("未能找到数据表主键！");
                    return;
                }
                dbHelper.Update(this.TableName, dtChanges);
                WinMessageBox.Show("数据保存成功！");
            }
            catch (Exception ex)
            {
                WinMessageBox.Show("数据保存异常：" + ex.Message);
            }
            this.LoadData();
        }

        void tbbDelete_Click(object sender, EventArgs e)
        {
            this.dataGridView1.EndEdit();
            if (this.dataGridView1.CurrentCell == null)
            {
                WinMessageBox.Show("请选择需要删除的数据！");
                return;
            }
            if (WinMessageBox.ShowQuestion("确认删除所选择的数据？") == false)
                return;
            try
            {
                OleDbHelper dbHelper = new OleDbHelper(this.DBFileName);
                DataTable dtColumns = dbHelper.GetColumns(this.TableName);
                /*数据表主键*/
                DataRow[] drPrimaryKeys = dtColumns.Select("PrimaryKey='1'");
                StringBuilder commandText = new StringBuilder();
                for (int i = this.dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
                {
                    DataRowView drv = this.dataGridView1.SelectedRows[i].DataBoundItem as DataRowView;

                    commandText = new StringBuilder();
                    if (drPrimaryKeys.Length > 0)
                    {
                        foreach (DataRow drColumn in drPrimaryKeys)
                        {
                            string fieldName = drColumn["Column_Name"].ToString();
                            string fieldValue = drv[fieldName].ToString();

                            if (commandText.ToString() != "")
                                commandText.Append(" and ");
                            commandText.Append(fieldName + "=@" + fieldName);

                            dbHelper.AddParam("@" + fieldName, fieldValue);
                        }
                    }
                    else
                    {
                        foreach (DataRow drColumn in dtColumns.Rows)
                        {
                            string fieldName = drColumn["Column_Name"].ToString();
                            string fieldValue = drv[fieldName].ToString();

                            if (commandText.ToString() != "")
                                commandText.Append(" and ");
                            commandText.Append(fieldName + "=@" + fieldName);

                            dbHelper.AddParam("@" + fieldName, fieldValue);
                        }
                    }
                    string delete = "Delete from " + this.TableName + " where " + commandText.ToString();
                    dbHelper.ExecuteNonQuery(delete);

                    int rowIndex = this.dataGridView1.SelectedRows[i].Index;
                    this.dataGridView1.Rows.RemoveAt(rowIndex);
                }
            }
            catch (Exception ex)
            {
                WinMessageBox.ShowError("删除数据异常：" + ex.Message);
            }
            this.LoadData();
        }

        private void LoadData()
        {
            try
            {
                this.dataGridView1.AutoGenerateColumns = true;
                this.dataGridView1.AllowUserToAddRows = false;
                FileInfo fileInfo = new FileInfo(this.DBFileName);

                OleDbHelper dbHelper = new OleDbHelper(DBFileName);
                dtData = dbHelper.ExecuteDataTable("Select * from " + TableName);
                this.dataGridView1.DataSource = dtData;
                /*数据表主键*/
                DataTable dtColumns = dbHelper.GetColumns(this.TableName);
                DataRow[] drPrimaryKeys = dtColumns.Select("PrimaryKey='1'");
                if (drPrimaryKeys.Length <= 0)
                {
                    //this.tbbDelete.Visible = false;
                    this.tbbSave.Visible = false;
                }
            }
            catch (Exception ex)
            {
                WinMessageBox.ShowError("加载数据异常：" + ex.Message);
            }

        }
    }
}
